package api

import (
	"github.com/labstack/echo/v4"
	"longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/const"
	string2 "longmen/server/pkg/common/helper/string"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

// @Summary 获取系统消息
// @Description 获取系统消息
// @Accept  json
// @Produce  json
// @Tags Notice
// @Param   sendBody body api_models.GetNoticeListReq true "body"
// @Success 0 {object} api_models.GetNoticeListResp "result"
// @Router /api/notice/getNoticeList [POST]
func (base *Controller) GetNoticeList(c echo.Context) error {
	user, err := base.GetUserByCtx(c)
	if err != nil {
		return util.BuildLoginTimeOut(c, err)
	}
	req := &api_models.GetNoticeListReq{}
	if err := util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(req); err != nil {
		return util.BadParam(c, err)
	}
	page := string2.GetDefaultNum(req.Page, 1)
	size := string2.GetDefaultNum(req.Size, 20)
	list, lastCreateTime, err := base.Service.GetNoticeList(user.Id, page, size)
	if user.ReadTime.Unix() < lastCreateTime {
		user.ReadTime = time.Now()
		if err = base.Service.UpdateUser([]string{"read_time"}, user); err != nil {
			global.Log.Errorf("uid:%d,更新最新阅读时间失败:%v", user.Id, err)
		}
		cache.UpdateUserReadTimeCache(user.Id, user.ReadTime)
	}
	return util.BuildSuccess(c, list, "")
}

// @Summary 获取最新系统消息简介
// @Description 获取最新系统消息简介
// @Accept  json
// @Produce  json
// @Tags Notice
// @Success 0 {object} api_models.GetNoticeResp "result"
// @Router /api/notice/getLatestNotice [POST]
func (base *Controller) GetLatestNotice(c echo.Context) error {
	user, err := base.GetUserByCtx(c)
	if err != nil {
		return util.BuildLoginTimeOut(c, err)
	}
	req := &api_models.GetNoticeListReq{}
	if err := util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(req); err != nil {
		return util.BadParam(c, err)
	}
	if err = base.Service.UpdateUser([]string{"read_time"}, user); err != nil {
		return util.BuildFail(c, 1, "更新最新阅读时间失败", err)
	}
	list, err := base.Service.GetLastNotice(user.Id)
	if err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	return util.BuildSuccess(c, list, "")
}
